﻿using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IPR_StudyMeetingMrgSys.Common
{
    public class ExcelHelper
    {
        private string fileName = null; //文件名
        private IWorkbook workbook = null;
        private FileStream fs = null;
        private bool disposed;

        public ExcelHelper(string fileName)
        {
            this.fileName = fileName.ToLower();
            disposed = false;
        }

        /// <summary>
        /// 将DataTable数据导入到excel中
        /// </summary>
        /// <param name="data">要导入的数据</param>
        /// <param name="isColumnWritten">DataTable的列名是否要导入</param>
        /// <param name="sheetName">要导入的excel的sheet的名称</param>
        /// <returns>导入数据行数(包含列名那一行)</returns>
        public int DataTableToExcel(DataTable data, string sheetName, bool isColumnWritten)
        {
            int i = 0;
            int j = 0;
            int count = 0;
            ISheet sheet = null;
            using (FileStream fileStream = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite))
            {
                if (Path.GetExtension(fileName) == ".xlsx") // 2007版本
                    workbook = new XSSFWorkbook(fileStream);
                else if (Path.GetExtension(fileName) == ".xls")// 2003版本
                    workbook = new HSSFWorkbook(fileStream);
                try
                {
                    sheet = workbook.CreateSheet(sheetName);
                    if (isColumnWritten == true) //写入DataTable的列名
                    {
                        IRow row = sheet.CreateRow(0);
                        for (j = 0; j < data.Columns.Count; ++j)
                        {
                            row.CreateCell(j).SetCellValue(data.Columns[j].ColumnName);
                        }
                        count = 1;
                    }
                    else
                    {
                        count = 0;
                    }

                    for (i = 0; i < data.Rows.Count; ++i)
                    {
                        IRow row = sheet.CreateRow(count);
                        for (j = 0; j < data.Columns.Count; ++j)
                        {
                            row.CreateCell(j).SetCellValue(data.Rows[i][j].ToString());
                        }
                        ++count;
                    }
                    workbook.Write(fs); //写入到excel
                    return count;
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }
        #region 将excel中的数据导入到DataTable中

        /// <summary>
        /// 将excel中的数据导入到DataTable中
        /// </summary>
        /// <param name="sheetIndex">excel工作薄sheet的索引，从0开始</param>
        /// <param name="columnNameIndex">excel工作薄sheet的列名索引，该索引为生成的Table列名，从下一索引开始读取数据，如参数为０时，从第一行开始</param>
        /// <returns>返回的DataTable</returns>
        public DataTable ExcelToDataTable(int sheetIndex, int columnNameIndex)
        {
            ISheet sheet = null;
            DataTable data = new DataTable();
            int startRow = columnNameIndex + 1;
            using (FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read))
            {
                try
                {
                    if (Path.GetExtension(fileName) == ".xlsx") // 2007版本
                        workbook = new XSSFWorkbook(fileStream);
                    else if (Path.GetExtension(fileName) == ".xls")// 2003版本
                        workbook = new HSSFWorkbook(fileStream);
                    sheet = workbook.GetSheetAt(sheetIndex);
                    if (sheet != null)
                    {
                        IRow columnName = sheet.GetRow(columnNameIndex);
                        int cellCount = columnName.LastCellNum; //一行最后一个cell的编号 即总的列数
                        for (int i = columnName.FirstCellNum; i < cellCount; ++i)
                        {
                            ICell cell = columnName.GetCell(i);
                            if (cell != null)
                            {
                                string cellValue = cell.StringCellValue;
                                if (!string.IsNullOrEmpty(cellValue))
                                {
                                    DataColumn column = new DataColumn(cellValue);
                                    data.Columns.Add(column);
                                }
                            }
                        }
                        //最后一行的标号
                        int rowCount = sheet.LastRowNum;
                        for (int i = startRow; i <= rowCount; ++i)
                        {
                            IRow row = sheet.GetRow(i);
                            //if (row == null) continue; //没有数据的行默认是null

                            //没有数据的行默认是null，跳出循环。row.Cells[0]索引从0开始，row.GetCell(1)索引从1开始
                            if (row == null || string.IsNullOrWhiteSpace(row.Cells[0].ToString())) break; 
                            DataRow dataRow = data.NewRow();
                            for (int j = row.FirstCellNum; j < cellCount; ++j)
                            {
                                if (row.GetCell(j) != null) //同理，没有数据的单元格都默认是null
                                    dataRow[j] = row.GetCell(j).ToString();
                            }
                            data.Rows.Add(dataRow);
                        }
                    }
                    return data;
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }
        #endregion

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing)
                {
                    if (fs != null)
                        fs.Close();
                }

                fs = null;
                disposed = true;
            }
        }
    }
}
